<template>
  <div class="node">
        <div class="leftCatalogue">
           <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
             @click="nodeAdd"
            >新增</el-button>
          <el-table
            v-if="refreshTable"
            v-loading="loading"
            :data="nodeList"
            row-key="id"
            :default-expand-all="isExpandAll"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          >
            <el-table-column prop="name" label="章节名" width="120px"></el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              ></el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              ></el-button>
            </template>
      </el-table-column>
          </el-table>
        </div>
        <div class="mainContent">
            <div>
              <el-input placeholder="请输入章节标题"   v-model="nodeForm.name" :disabled="noEdit" style="width: 65%"/>
              <span style="margin-left: 10px;">排序</span>
              <el-input-number  controls-position="right" :min="1"  v-model="nodeForm.sortCode"  style="width: 120px" :disabled="noEdit"/>
              <el-button type="primary" style="margin-left: 10px;" :disabled="noEdit" @click="submitForm">保存</el-button>
              <el-button type="primary"   @click="cancel">关闭</el-button>
            </div>
            <quill-editor
              v-model="nodeForm.content"
              ref="myQuillEditor"
              :options="editorOption"
              @focus="onEditorFocus($event)"
              @blur="onEditorBlur($event)"
              @change="onEditorChange($event)"
              class="editor"
            ></quill-editor>

            <form action method="post" enctype="multipart/form-data" id="uploadFormMulti">
              <input
                style="display: none"
                :id="uniqueId"
                type="file"
                name="file"
                multiple
                accept="image/jpg, image/jpeg, image/png, image/gif"
                @change="uploadImg('uploadFormMulti')"
              />
            </form>
        </div>
      </div>
</template>

<script>
import {selectCourseNodeApi,deleteCourseNodeApi,addCourseNodeApi,updateCourseNodeApi} from "@/api/system/course"
import {uploadApi} from "@/api/system/common"
import {base} from "@/utils/request"
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import Quill from "quill";
import ImageResize from "quill-image-resize-module"; // 引用
import { ImageDrop } from "quill-image-drop-module";
Quill.register("modules/imageDrop", ImageDrop);
Quill.register("modules/imageResize", ImageResize); // 注册
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
  [{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ script: "sub" }, { script: "super" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{ indent: "-1" }, { indent: "+1" }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{ direction: "rtl" }], // 文本方向-----[{'direction': 'rtl'}]
  [{ size: ["small", false, "large", "huge"] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{ font: [] }], // 字体种类-----[{ font: [] }]
  [{ align: [] }], // 对齐方式-----[{ align: [] }]
  ["clean"], // 清除文本格式-----['clean']
  ["image", "video"] // 链接、图片、视频-----['link', 'image', 'video']
];
export default {
  name: 'nodeEditor',
  components: {
    quillEditor
  },
  data() {
    return {
       // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      refreshTable: true,
      // 表格数据
      nodeList: [],
      //  // 菜单树选项
      // 是否展开，默认全部展开
      isExpandAll: true,
      uniqueId: "uniqueId",
      noEdit:true,
      //富文本编辑器配置
     editorOption: {
        theme: "snow",
        placeholder: "请输入正文",
        modules: {
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white"
            },
            modules: ["Resize", "DisplaySize", "Toolbar"]
          },
          //  富文本编辑器配置
          toolbar: {
            container: toolbarOptions
          }
        }
      },
      nodeForm:{},
    };
  },
  props: {
    courseId: {
      type: String,
      required: true
    },
    openNode: {
      type: Boolean,
      required: true
    }
  },
  created() {
    this.selectCourseNode();
    this.nodeForm.courseId = this.courseId;
    this.reset();
  },
  computed: {
    //当前富文本实例
    editor() {
      return this.$refs.myQuillEditor.quill;
    }
  },
  methods: {
    //查询
    selectCourseNode(){
      selectCourseNodeApi({
        'courseId':this.courseId
      }).then(data=>{
        this.nodeList=  data.data;
        this.loading = false;
      }).catch(()=>{
        this.loading = false;
      })
    },
     /** 修改按钮操作 */
    handleUpdate(row) {
        this.reset();
        this.nodeForm.name = row.name;
        this.nodeForm.id = row.id;
        this.nodeForm.sortCode = row.sortCode;
        this.nodeForm.content = row.content;
        this.noEdit = false;
    },
     /** 修改按钮操作 */
    nodeAdd(row) {
        this.reset();
        this.noEdit = false;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除章节为"' + row.name + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=> {
          deleteCourseNodeApi({
            "id": row.id
          }).then(data=>{
            this.reset();
            this.noEdit = true;
            this.selectCourseNode();
            this.$message({
               type: 'success',
              message: '删除成功'
            });
          })
        })
    },
     /** 提交按钮 */
    submitForm: function() {
          if (this.nodeForm.id != undefined) {
            updateCourseNodeApi(this.nodeForm).then(data=>{
              this.selectCourseNode();
              this.$message({
                type: 'success',
                message: '修改成功'
              });
            })
          } else {
            addCourseNodeApi(this.nodeForm).then(data=>{
              this.selectCourseNode();
              this.reset();
              this.noEdit = true;
              this.$message({
                type: 'success',
                message: '添加成功'
              });
            })
          }
    }, // 取消按钮
     reset() {
      this.nodeForm = {
        courseId:this.courseId,
        id:undefined,
        name: undefined,
        sortCode: undefined,
        content: undefined
      };
    },
    cancel() {
      this.$confirm('是否确认关闭章节窗口，请注意保存内容?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=> {
          this.reset();
          this.noEdit= true;
          this.$emit('closeMain',false); 
        
        })
    },
    //失去焦点事件
    onEditorBlur(quill) {
      
    },
    //获得焦点事件
    onEditorFocus(quill) {
      if(this.noEdit){
         this.editor.enable(false);
         return;
      }else{
         this.editor.enable(true);
      }
     
      
    },
   // 准备富文本编辑器
    onEditorReady(quill) {
      
     },
    //内容改变事件
     onEditorChange({ quill, html, text }) {
       this.nodeForm.content = html
     },
     uploadImg: async function() {
       if(this.noEdit){
         console.log(5555)
         this.$message({
            type: 'success',
            message: '目前不能上传图片'
          });
         return;
       }
      var _this = this;
      //构造formData对象
      var formData = new FormData();
      formData.append("file", document.getElementById(_this.uniqueId).files[0]);

      try {
        //调用上传文件接口
        uploadApi(formData).then(data => {
          //返回上传文件的地址
          if(data.code == '200'){
            let url = base+"/image/"+data.data;
            let Range = _this.editor.getSelection();
            // //上传文件成功之后在富文本中回显(显示)
            _this.editor.insertEmbed(
              Range != null ? Range.index : 0,
              "image",
              url
            );
          }
          document.getElementById(_this.uniqueId).value = "";
        });
      } catch ({ message: msg }) {
        document.getElementById(_this.uniqueId).value = "";
        _this.$message.warning(msg);
      }
    }
  },
  mounted() {
    var _this = this;
    var imgHandler = async function(image) {

      if (image) {
        var fileInput = document.getElementById(_this.uniqueId); //隐藏的file文本ID
        fileInput.click(); //加一个触发事件
      }
    };
    _this.editor.getModule("toolbar").addHandler("image", imgHandler);
  }
};
</script>

<style>
 .node{
   display: flex;
  }
  .leftCatalogue{
    width: 19%;
    height: 64vh;
  }
  .mainContent{
    width: 79%;
    height: 58vh;
  }
  .editor {
    line-height: normal !important;
    margin-top: 10px;
    height: 90%;
  }
  .ql-snow .ql-tooltip[data-mode="link"]::before {
    content: "请输入链接地址:";
  }
  .ql-snow .ql-tooltip.ql-editing a.ql-action::after {
    border-right: 0px;
    content: "保存";
    padding-right: 0px;
  }

  .ql-snow .ql-tooltip[data-mode="video"]::before {
    content: "请输入视频地址:";
  }

  .ql-snow .ql-picker.ql-size .ql-picker-label::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item::before {
    content: "14px";
  }
  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="small"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="small"]::before {
    content: "10px";
  }
  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="large"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="large"]::before {
    content: "18px";
  }
  .ql-snow .ql-picker.ql-size .ql-picker-label[data-value="huge"]::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item[data-value="huge"]::before {
    content: "32px";
  }

  .ql-snow .ql-picker.ql-header .ql-picker-label::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item::before {
    content: "文本";
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before {
    content: "标题1";
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before {
    content: "标题2";
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before {
    content: "标题3";
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before {
    content: "标题4";
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before {
    content: "标题5";
  }
  .ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before,
  .ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before {
    content: "标题6";
  }

  .ql-snow .ql-picker.ql-font .ql-picker-label::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item::before {
    content: "标准字体";
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="serif"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="serif"]::before {
    content: "衬线字体";
  }
  .ql-snow .ql-picker.ql-font .ql-picker-label[data-value="monospace"]::before,
  .ql-snow .ql-picker.ql-font .ql-picker-item[data-value="monospace"]::before {
    content: "等宽字体";
  }
</style>